package com.phei.netty.codec.marshalling;

import com.phei.netty.codec.pojo.Request;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.CountDownLatch;


public class SubReqClientHandler extends ChannelHandlerAdapter {
    CountDownLatch countDownLatch;

    /**
     * Creates a client-side handler.
     */
    public SubReqClientHandler(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }


    public void channelActive(ChannelHandlerContext ctx) {
        ctx.write(new Request());
        ctx.flush();
    }


    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        System.out.println("Receive server response : [" + msg + "]");
        this.countDownLatch.countDown();
    }


    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
        this.countDownLatch.countDown();
    }
}
